package wxdb.parse.absyn;
import java.util.*;

import wxdb.symbol.Symbol;
import wxdb.ui.Global;
public class FldsExp extends Exp{
	public FldExp fldExp;
	public FldsExp tail;
	
	private HashMap<String, ArrayList<String>> fields = new HashMap<String,ArrayList<String>>();
	private HashMap<String, String> fldNameToNick = new HashMap<String, String>();
	private ArrayList<String> fldNameList = new ArrayList<String>();
	private ArrayList<Integer> operList = new ArrayList<Integer>();
	private ArrayList<String> nickNameList = new ArrayList<String>();
	
	public FldsExp(int p, FldExp fe, FldsExp fse){
		pos = p;
		fldExp = fe;
		tail = fse;
	}
	
	public HashMap<String, ArrayList<String>> getFileds(String tn){
		FldsExp fse = this; 
		FldExp fe;
		String tblName = "";
		Symbol tblSym = null;
		String fldName = "";
		Symbol nickName = null;
		while(fse!=null){
			fe = fse.fldExp;
			if(fe instanceof NameFldExp){
				tblSym = ((NameFldExp)fe).getTableName();
				fldName = ((NameFldExp)fe).getName();
				nickName = ((NameFldExp)fe).nickName;
				if(tblSym == null)
					tblName = tn;
				else
					tblName = tblSym.toString();
				if(!fields.containsKey(tblName)){
					ArrayList<String> al = new ArrayList<String>();
					al.add(fldName);
					fields.put(tblName, al);
				}else{
					fields.get(tblName).add(fldName);
				}
			}else if(fe instanceof FuncFldExp){
				tblSym = ((NameFldExp)(((FuncFldExp)fe).tail)).getTableName();
				fldName = ((NameFldExp)(((FuncFldExp)fe).tail)).getName();
				if(tblSym == null)
					tblName = tn;
				else
					tblName = tblSym.toString();
				if(!fields.containsKey(tblName)){
					ArrayList<String> al = new ArrayList<String>();
					al.add(fldName);
					fields.put(tblName, al);
				}else{
					fields.get(tblName).add(fldName);
				}
				Global.computefield = fldName;
				Global.asfield = ((FuncFldExp)fe).nickName.toString();
				int option = ((FuncFldExp)fe).funcExp.option;
				if(option == BinOper.AVG)
					Global.AVG = true;
				else if(option == BinOper.COUNT)
					Global.COUNT = true;
				else if(option == BinOper.MAX)
					Global.MAX = true;
				else if(option == BinOper.MIN)
					Global.MIN = true;
				else if(option == BinOper.SUM)
					Global.SUM = true;
				fldNameList.add(fldName);
				operList.add(((FuncFldExp)fe).funcExp.option);
				nickNameList.add(((FuncFldExp)fe).nickName.toString());
			}
			if(nickName != null){
				fldNameToNick.put(tblName+fldName, nickName.toString());
				nickName = null;
			}
			fse = fse.tail;
		}
		return fields;
	}
	
	//you must first call getFileds before call this getNickName
	public HashMap<String, String> getNickName(){
		return fldNameToNick;
	}
}
